/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.facilscrum.form.usuarios;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.view.JasperViewer;
import org.javscaz.javscaztools.utilidades.Utilidades;
import org.facilscrum.beans.Departamento;
import org.facilscrum.beans.Gruposusuarios;
import org.facilscrum.beans.Usuarios;
import org.facilscrum.controller.DepartamentoController;
import org.facilscrum.controller.GruposusuariosController;
import org.facilscrum.controller.UsuariosController;
import org.facilscrum.generales.Mensajeria;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;

/**
 *
 * @author avbravo
 */
public class UsuariosForm extends javax.swing.JInternalFrame {

    DepartamentoController departamentoController = new DepartamentoController();
    GruposusuariosController gruposusuariosController = new GruposusuariosController();
    UsuariosController usuariosController = new UsuariosController();
    Usuarios usuarios = new Usuarios();
    DefaultTableModel modelo;
    String query = "all";
   

    /**
     * Creates new form UsuariosForm
     */
    public UsuariosForm() {
        initComponents();
         jLabelMensaje.setText("");
        modelo = (DefaultTableModel) jTable1.getModel();
        cargarTabla(query);
        if (cargarComboDepartamento() && cargarComboGrupoUsuario()) {
        } else {
            jTextFieldUsername.setEnabled(false);
            jButtonConsultar.setEnabled(false);
            jButtonLimpiar.setEnabled(false);
        }
        habilitarEncontrado(false);
        jButtonAgregar.setEnabled(false);
        AutoCompleteDecorator.decorate(jComboBoxActivo);
        AutoCompleteDecorator.decorate(jComboBoxDepartamento);
        AutoCompleteDecorator.decorate(jComboBoxGrupoUsuario);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextFieldUsername = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jTextFieldNombre = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jTextFieldCargo = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jTextFieldEmail = new javax.swing.JTextField();
        jButtonConsultar = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jComboBoxActivo = new javax.swing.JComboBox();
        jLabel8 = new javax.swing.JLabel();
        jComboBoxGrupoUsuario = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        jComboBoxDepartamento = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel10 = new javax.swing.JLabel();
        jTextFieldCedula = new javax.swing.JTextField();
        jPasswordField = new javax.swing.JPasswordField();
        jButtonAgregar = new javax.swing.JButton();
        jButtonModificar = new javax.swing.JButton();
        jButtonLimpiar = new javax.swing.JButton();
        jButtonEliminar = new javax.swing.JButton();
        jButtonCerrar = new javax.swing.JButton();
        jButtonImprimir = new javax.swing.JButton();
        jButtonImprimirTodos = new javax.swing.JButton();
        jButtonFiltroDepartamento = new javax.swing.JButton();
        jButtonGrupo = new javax.swing.JButton();
        jButtonQuitarFiltro = new javax.swing.JButton();
        jButtonGrupo1 = new javax.swing.JButton();
        jLabelMensaje = new javax.swing.JLabel();
        jButtonFiltroDepartamento1 = new javax.swing.JButton();
        jButtonRefrescarDepartamento = new javax.swing.JButton();

        setClosable(true);
        setTitle("Usuarios");

        jLabel1.setText("username");

        jTextFieldUsername.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldUsernameActionPerformed(evt);
            }
        });

        jLabel2.setText("Password");

        jLabel4.setText("Nombre");

        jLabel5.setText("Cargo");

        jLabel6.setText("Email");

        jButtonConsultar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/avbravo/jscrum/gif/search.png"))); // NOI18N
        jButtonConsultar.setToolTipText("Consultar");
        jButtonConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonConsultarActionPerformed(evt);
            }
        });

        jLabel7.setText("Activo");

        jComboBoxActivo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "si", "no" }));

        jLabel8.setText("Grupo");

        jLabel9.setText("Departamento");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Username", "Cedula", "Nombre", "Grupo", "Departamento", "Activo"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jLabel10.setText("Cedula");

        jPasswordField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jPasswordFieldActionPerformed(evt);
            }
        });
        jPasswordField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jPasswordFieldKeyPressed(evt);
            }
        });

        jButtonAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/avbravo/jscrum/gif/save_icon.gif"))); // NOI18N
        jButtonAgregar.setToolTipText("Agregar");
        jButtonAgregar.setEnabled(false);
        jButtonAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAgregarActionPerformed(evt);
            }
        });

        jButtonModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/avbravo/jscrum/gif/edit.png"))); // NOI18N
        jButtonModificar.setToolTipText("Modificar");
        jButtonModificar.setEnabled(false);
        jButtonModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonModificarActionPerformed(evt);
            }
        });

        jButtonLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/avbravo/jscrum/gif/clear.png"))); // NOI18N
        jButtonLimpiar.setToolTipText("Limpiar");
        jButtonLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonLimpiarActionPerformed(evt);
            }
        });

        jButtonEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/avbravo/jscrum/gif/delete.gif"))); // NOI18N
        jButtonEliminar.setToolTipText("Eliminar");
        jButtonEliminar.setEnabled(false);
        jButtonEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEliminarActionPerformed(evt);
            }
        });

        jButtonCerrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/avbravo/jscrum/gif/return.gif"))); // NOI18N
        jButtonCerrar.setToolTipText("Cerrar");
        jButtonCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCerrarActionPerformed(evt);
            }
        });

        jButtonImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/facilscrum/gif/x16/print.png"))); // NOI18N
        jButtonImprimir.setEnabled(false);
        jButtonImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonImprimirActionPerformed(evt);
            }
        });

        jButtonImprimirTodos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/facilscrum/gif/x16/print.png"))); // NOI18N
        jButtonImprimirTodos.setText("Todos");
        jButtonImprimirTodos.setToolTipText("Imprimir todos");
        jButtonImprimirTodos.setEnabled(false);
        jButtonImprimirTodos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonImprimirTodosActionPerformed(evt);
            }
        });

        jButtonFiltroDepartamento.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/facilscrum/gif/x16/filter.png"))); // NOI18N
        jButtonFiltroDepartamento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonFiltroDepartamentoActionPerformed(evt);
            }
        });

        jButtonGrupo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/facilscrum/gif/x16/filter.png"))); // NOI18N
        jButtonGrupo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGrupoActionPerformed(evt);
            }
        });

        jButtonQuitarFiltro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/facilscrum/gif/x16/filtro_delete.png"))); // NOI18N
        jButtonQuitarFiltro.setToolTipText("Eliminar filtro");
        jButtonQuitarFiltro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonQuitarFiltroActionPerformed(evt);
            }
        });

        jButtonGrupo1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/facilscrum/gif/x16/filter.png"))); // NOI18N
        jButtonGrupo1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGrupo1ActionPerformed(evt);
            }
        });

        jLabelMensaje.setText("...");

        jButtonFiltroDepartamento1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/facilscrum/gif/x16/page_refresh.png"))); // NOI18N
        jButtonFiltroDepartamento1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonFiltroDepartamento1ActionPerformed(evt);
            }
        });

        jButtonRefrescarDepartamento.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/facilscrum/gif/x16/page_refresh.png"))); // NOI18N
        jButtonRefrescarDepartamento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRefrescarDepartamentoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel1))
                                .addGap(63, 63, 63)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(jTextFieldUsername, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jButtonConsultar)
                                        .addGap(18, 18, 18)
                                        .addComponent(jLabelMensaje, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(jPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel6)
                                    .addComponent(jLabel4)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGap(33, 33, 33)
                                        .addComponent(jLabel7))
                                    .addComponent(jLabel10))
                                .addGap(58, 58, 58)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jTextFieldCedula, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jTextFieldEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jTextFieldNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 294, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jTextFieldCargo, javax.swing.GroupLayout.PREFERRED_SIZE, 333, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jComboBoxDepartamento, javax.swing.GroupLayout.PREFERRED_SIZE, 346, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(jComboBoxActivo, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jButtonGrupo1)))))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel8)
                                .addGap(90, 90, 90)
                                .addComponent(jComboBoxGrupoUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 307, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButtonFiltroDepartamento1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonGrupo))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButtonRefrescarDepartamento)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonFiltroDepartamento))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addGap(61, 61, 61)
                                .addComponent(jButtonAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonImprimir)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonImprimirTodos)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonQuitarFiltro)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jButtonCerrar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addGap(33, 33, 33))))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 539, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jButtonConsultar)
                        .addComponent(jLabel1)
                        .addComponent(jTextFieldUsername, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabelMensaje))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(jLabel2))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel10)
                    .addComponent(jTextFieldCedula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(jLabel4))
                    .addComponent(jTextFieldNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(4, 4, 4)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(jLabel5))
                    .addComponent(jTextFieldCargo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(4, 4, 4)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(jLabel6))
                    .addComponent(jTextFieldEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(9, 9, 9)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGap(7, 7, 7)
                                        .addComponent(jLabel9))
                                    .addComponent(jButtonFiltroDepartamento)
                                    .addComponent(jButtonRefrescarDepartamento))
                                .addGap(2, 2, 2))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jComboBoxDepartamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(2, 2, 2)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jComboBoxGrupoUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButtonGrupo)
                            .addComponent(jLabel8)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonFiltroDepartamento1)))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jComboBoxActivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel7))
                    .addComponent(jButtonGrupo1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButtonCerrar)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jButtonModificar)
                                .addComponent(jButtonEliminar)
                                .addComponent(jButtonLimpiar))
                            .addComponent(jButtonImprimir)
                            .addComponent(jButtonImprimirTodos))
                        .addComponent(jButtonQuitarFiltro))
                    .addComponent(jButtonAgregar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(26, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 9, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAgregarActionPerformed
        try {
            if (!guiToData()) {
                return;
            }
            if (usuariosController.insert(usuarios)) {
                Mensajeria.Mensaje("Se guardo exitosamente");
                habilitarEncontrado(true);
                cargarTabla(query);
            } else {
                Mensajeria.MensajeWarning("No se pudo guardar " + usuariosController.getMensaje());
            }
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "agregar()");
        }
    }//GEN-LAST:event_jButtonAgregarActionPerformed

    private void jButtonModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonModificarActionPerformed
        try {
            if (!guiToData()) {
                return;
            }
            if (usuariosController.update(usuarios)) {
                Mensajeria.Mensaje("Se actualizo  exitosamente");
                habilitarEncontrado(true);

                cargarTabla(query);

            } else {
                Mensajeria.MensajeWarning("No se pudo actualizar " + usuariosController.getMensaje());
            }
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "modificar()");
        }
    }//GEN-LAST:event_jButtonModificarActionPerformed

    private void jButtonLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLimpiarActionPerformed
        limpiar();
         jTextFieldUsername.setText("");
        habilitarEncontrado(false);
    }//GEN-LAST:event_jButtonLimpiarActionPerformed

    private void jButtonEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEliminarActionPerformed
        try {
            guiToData();
            if (Mensajeria.PreguntaSiNo("Desea eliminar el usuario", "Eliminar").equals("no")) {
                Mensajeria.Mensaje("No se elimino el usuario");
                return;
            }
            if (usuariosController.delete(usuarios)) {
                Mensajeria.Mensaje("Se elimino exitosamente");
                limpiar();
                 jTextFieldUsername.setText("");
                habilitarEncontrado(false);
                cargarTabla(query);
            } else {
                Mensajeria.MensajeWarning("No se pudo eliminar " + usuariosController.getMensaje());
            }
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "eliminar()");
        }
    }//GEN-LAST:event_jButtonEliminarActionPerformed

    private void jButtonCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCerrarActionPerformed
        dispose();
    }//GEN-LAST:event_jButtonCerrarActionPerformed

    private void jTextFieldUsernameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldUsernameActionPerformed
        consultar();
    }//GEN-LAST:event_jTextFieldUsernameActionPerformed

    private void jButtonConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonConsultarActionPerformed
        consultar();
    }//GEN-LAST:event_jButtonConsultarActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        try {
            Integer fila = jTable1.getSelectedRow();
            if (fila == -1) {
                Mensajeria.Mensaje("No se selecciono ninguna fila");
                return;
            }
            jTextFieldUsername.setText(jTable1.getValueAt(fila, 0).toString());
            consultar();
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "MouseClicked()");
        }
    }//GEN-LAST:event_jTable1MouseClicked

    private void jButtonImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonImprimirActionPerformed
        HashMap map = new HashMap();
        List<Usuarios> list = new ArrayList();
        list.add(usuarios);
        try {
            imprimir(list, map);
        } catch (JRException ex) {
            Logger.getLogger(UsuariosForm.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_jButtonImprimirActionPerformed

    private void jButtonImprimirTodosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonImprimirTodosActionPerformed
        HashMap map = new HashMap();

        try {
            imprimirTodos(usuariosController.getUsuarioslist(), map);
        } catch (JRException ex) {
            Mensajeria.MensajeError(ex, "Boton imprimir()");
        }
    }//GEN-LAST:event_jButtonImprimirTodosActionPerformed

    private void jButtonQuitarFiltroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonQuitarFiltroActionPerformed
        query = "all";
        cargarTabla(query);
    }//GEN-LAST:event_jButtonQuitarFiltroActionPerformed

    private void jButtonFiltroDepartamentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFiltroDepartamentoActionPerformed
        try {
            Integer i = jComboBoxDepartamento.getSelectedIndex();
            if (i != -1) {
                Departamento d = departamentoController.getDepartamentolist().get(i);
                //  String iddepartamento= jComboBoxDepartamento.getSelectedItem().toString();
                query = "iddepartamento='" + d.getIddepartamento() + "'";
                cargarTabla(query);
            }

        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "Filtro()");
        }

    }//GEN-LAST:event_jButtonFiltroDepartamentoActionPerformed

    private void jButtonGrupoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGrupoActionPerformed
        try {
            Integer i = jComboBoxGrupoUsuario.getSelectedIndex();
            if (i != -1) {
                // String idgrupousuario= jComboBoxGrupoUsuario.getSelectedItem().toString();
                Gruposusuarios g = gruposusuariosController.getGruposusuarioslist().get(i);
                query = "idgruposusuario='" + g.getIdgruposusuario() + "'";
                cargarTabla(query);
            }

        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "Filtro()");
        }        // TODO add your handling code here:
    }//GEN-LAST:event_jButtonGrupoActionPerformed

    private void jButtonGrupo1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGrupo1ActionPerformed
        try {
            Integer i = jComboBoxActivo.getSelectedIndex();
            if (i != -1) {
                String activo = jComboBoxActivo.getSelectedItem().toString();

                query = "activo='" + activo + "'";
                cargarTabla(query);
            }

        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "Filtro()");
        }
    }//GEN-LAST:event_jButtonGrupo1ActionPerformed

    private void jPasswordFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPasswordFieldActionPerformed
jLabelMensaje.setText("");
    }//GEN-LAST:event_jPasswordFieldActionPerformed

    private void jPasswordFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordFieldKeyPressed
jLabelMensaje.setText("");
       
    }//GEN-LAST:event_jPasswordFieldKeyPressed

    private void jButtonFiltroDepartamento1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFiltroDepartamento1ActionPerformed
 cargarComboGrupoUsuario();
    }//GEN-LAST:event_jButtonFiltroDepartamento1ActionPerformed

    private void jButtonRefrescarDepartamentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRefrescarDepartamentoActionPerformed
cargarComboDepartamento() ;
    }//GEN-LAST:event_jButtonRefrescarDepartamentoActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAgregar;
    private javax.swing.JButton jButtonCerrar;
    private javax.swing.JButton jButtonConsultar;
    private javax.swing.JButton jButtonEliminar;
    private javax.swing.JButton jButtonFiltroDepartamento;
    private javax.swing.JButton jButtonFiltroDepartamento1;
    private javax.swing.JButton jButtonGrupo;
    private javax.swing.JButton jButtonGrupo1;
    private javax.swing.JButton jButtonImprimir;
    private javax.swing.JButton jButtonImprimirTodos;
    private javax.swing.JButton jButtonLimpiar;
    private javax.swing.JButton jButtonModificar;
    private javax.swing.JButton jButtonQuitarFiltro;
    private javax.swing.JButton jButtonRefrescarDepartamento;
    private javax.swing.JComboBox jComboBoxActivo;
    private javax.swing.JComboBox jComboBoxDepartamento;
    private javax.swing.JComboBox jComboBoxGrupoUsuario;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JLabel jLabelMensaje;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPasswordField jPasswordField;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextFieldCargo;
    private javax.swing.JTextField jTextFieldCedula;
    private javax.swing.JTextField jTextFieldEmail;
    private javax.swing.JTextField jTextFieldNombre;
    private javax.swing.JTextField jTextFieldUsername;
    // End of variables declaration//GEN-END:variables

    private void imprimir(List<Usuarios> aux, HashMap map) throws JRException {
        try {
            JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(aux);
//Indicamos la ruta del reporte
            InputStream reporte = (InputStream) getClass().getResourceAsStream("/org/facilscrum/reportes/usuarios.jasper");
            if (reporte == null) {
                Mensajeria.Mensaje("No se pudo cargar el reporte");
            } else {
                JasperPrint print = JasperFillManager.fillReport(reporte, map, ds);
                JasperViewer.viewReport(print, false);
            }
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "Imprimir()");
        }
    }

    private void imprimirTodos(List<Usuarios> aux, HashMap map) throws JRException {
        try {
            JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(aux);
//Indicamos la ruta del reporte
            InputStream reporte = (InputStream) getClass().getResourceAsStream("/org/facilscrum/reportes/usuariostodos.jasper");
            if (reporte == null) {
                Mensajeria.Mensaje("No se pudo cargar el reporte");
            } else {
                JasperPrint print = JasperFillManager.fillReport(reporte, map, ds);
                JasperViewer.viewReport(print, false);
            }
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "Imprimir()");
        }
    }

    private Boolean guiToData() {
        try {
            if (jTextFieldUsername.getText() == null || jTextFieldUsername.getText().equals("")) {
                Mensajeria.Mensaje("El username no debe estar vacio");
                return false;
            }
            String password = new String(this.jPasswordField.getPassword());
            if (password == null || password.equals("")) {
                Mensajeria.Mensaje("El password no debe estar vacio");
                return false;
            }
            if (jTextFieldCedula.getText() == null || jTextFieldCedula.getText().equals("")) {
                Mensajeria.Mensaje("La cedula no debe estar vacio");
                return false;
            }
            if (jTextFieldNombre.getText() == null || jTextFieldNombre.getText().equals("")) {
                Mensajeria.Mensaje("El nombre no debe estar vacio");
                return false;
            }
            if (jTextFieldCargo.getText() == null || jTextFieldCargo.getText().equals("")) {
                Mensajeria.Mensaje("El cargo no debe estar vacio");
                return false;
            }

            usuarios.setActivo(jComboBoxActivo.getSelectedItem().toString());
            usuarios.setCargo(jTextFieldCargo.getText());
            usuarios.setEmail(jTextFieldEmail.getText());
            usuarios.setNombre(jTextFieldNombre.getText());

            usuarios.setPassword(password);
            usuarios.setUsername(jTextFieldUsername.getText());
            usuarios.setCedula(jTextFieldCedula.getText());

            int i = jComboBoxDepartamento.getSelectedIndex();
            if (i != -1) {
                Departamento departamento = departamentoController.getDepartamentolist().get(i);
                usuarios.setIddepartamento(departamento.getIddepartamento());
            } else {
                Mensajeria.Mensaje("No se ha seleccionado ningun departamento");
                return false;
            }
            int j = jComboBoxGrupoUsuario.getSelectedIndex();
            if (j != -1) {
                Gruposusuarios gruposusuarios = gruposusuariosController.getGruposusuarioslist().get(j);
                usuarios.setIdgruposusuario(gruposusuarios.getIdgruposusuario());
            } else {
                Mensajeria.Mensaje("No se ha seleccionado ningun grupo de usuario");
                return false;
            }
            return true;
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "guiToData");
        }
        return false;
    }

    private void cargarTabla(String query) {
        try {
            modelo = Utilidades.limpiarModelo(modelo);
            switch (query) {
                case "all":
                    if (usuariosController.selectAll()) {
                        rellenarModelo(usuariosController);
                    }
                    break;
                default:
                    if (usuariosController.query(query)) {
                        rellenarModelo(usuariosController);
                    }
                    break;
            }
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "cargarTabla()");
        }
    }

    private void rellenarModelo(UsuariosController uc) {
        try {
            for (Usuarios u : uc.getUsuarioslist()) {
                Object[] filas = new Object[6]; // Hay tres columnas en la tabla       
                filas[0] = u.getUsername();
                filas[1] = u.getCedula();
                filas[2] = u.getNombre();
                filas[3] = u.getDepartamento().getDepartamento();
                filas[4] = u.getGruposusuarios().getGruposusuario();
                filas[5] = u.getActivo();
                modelo.addRow(filas);
            }
            jButtonImprimirTodos.setEnabled(true);
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "rellenarModelo()");
        }
    }

    private Boolean cargarComboDepartamento() {
        try {
            jComboBoxDepartamento.removeAllItems();
            if (departamentoController.selectAll()) {
                jComboBoxDepartamento.removeAllItems();
                for (Departamento d : departamentoController.getDepartamentolist()) {
                    jComboBoxDepartamento.addItem(d.getDepartamento());
                }
                return true;
            } else {
                Mensajeria.Mensaje("Debe crear primero los departamentos ");
            }
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "cargarComboDepartamento()");

        }
        return false;
    }

    private Boolean cargarComboGrupoUsuario() {
        try {
            jComboBoxGrupoUsuario.removeAllItems();
            if (gruposusuariosController.selectAll()) {
                jComboBoxGrupoUsuario.removeAllItems();

                for (Gruposusuarios g : gruposusuariosController.getGruposusuarioslist()) {
                    jComboBoxGrupoUsuario.addItem(g.getGruposusuario());
                }
                return true;
            } else {
                Mensajeria.Mensaje("Debe crear primero los grupos de usuarios ");
            }
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "cargarComboGrupoUsuario() ");

        }
        return false;
    }

    private Boolean consultar() {
        try {
            if (jTextFieldUsername.getText() == null || jTextFieldUsername.getText().equals("")) {
                Mensajeria.MensajeWarning("Debe ingresar el username");
                jTextFieldUsername.requestFocus();
                return false;
            }
            usuarios.setUsername(jTextFieldUsername.getText());
            Usuarios u = usuariosController.findByPrimaryKey(usuarios);
            if (u != null) {
                usuarios = u;
                jTextFieldUsername.setText(usuarios.getUsername());
                jTextFieldCargo.setText(usuarios.getCargo());
                jTextFieldCedula.setText(usuarios.getCedula());
                jTextFieldEmail.setText(usuarios.getEmail());
                jTextFieldNombre.setText(usuarios.getNombre());
                jComboBoxActivo.setSelectedItem(usuarios.getActivo());
                jPasswordField.setText(usuarios.getPassword());

                jComboBoxGrupoUsuario.setSelectedItem(usuarios.getGruposusuarios().getGruposusuario());
                jComboBoxDepartamento.setSelectedItem(usuarios.getDepartamento().getDepartamento());
                habilitarEncontrado(true);
                habilitarCajasTexto(true);
            } else {
                //Mensajeria.MensajeWarning("No existe registro con ese username");
                 jLabelMensaje.setText("No existe registro con ese username");
                habilitarEncontrado(false);
                limpiar();
                habilitarCajasTexto(true);
                jButtonAgregar.setEnabled(true);
            }
            return true;
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "consultar()");
        }
        return false;
    }

    private void habilitarEncontrado(Boolean encontrado) {
        if(jTextFieldUsername.getText().equals("")){
                  jButtonAgregar.setEnabled(false);
        }else{
                  jButtonAgregar.setEnabled(!encontrado);
        }
  
        jButtonModificar.setEnabled(encontrado);
        jButtonEliminar.setEnabled(encontrado);
        jButtonImprimir.setEnabled(encontrado);

    }

    private void habilitarCajasTexto(Boolean encontrado) {
        jTextFieldCargo.setEnabled(encontrado);
        jTextFieldCedula.setEnabled(encontrado);
        jTextFieldEmail.setEnabled(encontrado);
        jTextFieldNombre.setEnabled(encontrado);
        jPasswordField.setEnabled(encontrado);
        jComboBoxActivo.setEnabled(encontrado);
        jComboBoxDepartamento.setEnabled(encontrado);
        jComboBoxGrupoUsuario.setEnabled(encontrado);
    }

    private void limpiar() {
       
        jTextFieldCargo.setText("");
        jTextFieldCedula.setText("");
        jTextFieldEmail.setText("");
        jTextFieldNombre.setText("");
        jPasswordField.setText("");
        jButtonAgregar.setEnabled(false);
        habilitarCajasTexto(false);
    }
}
